package com.zmn.plat.admin.controller.product;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.common.dto.ResultDTO;
import com.zmn.plat.admin.config.Ueditor;
import com.zmn.plat.admin.config.UeditorConfig;
import com.zmn.plat.business.interfaces.pic.PicUploadBService;

/**
 * 类描述: Ueditor后台控制类
 *
 * @author linfeng
 * @since 2019/08/29/9:08
 */
@Controller
public class ServUeditorController {
    private Logger logger = LoggerFactory.getLogger(ServUeditorController.class);

    @Resource
    PicUploadBService picUploadBService;

    @RequestMapping(value = "/ueditor", produces = "application/text;charset=UTF-8")
    @ResponseBody
    public String ueditor(@RequestParam("action") String param, MultipartFile upfile, HttpServletRequest request) {
        Ueditor ueditor = new Ueditor();
        if (param != null && param.equals("config")) {
            return UeditorConfig.UEDITOR_CONFIG;
        } else if (param != null && param.equals("uploadimage") || param.equals("uploadscrawl")) {
            if (upfile != null) {
                // {state：”数据状态信息”，url：”图片回显路径”，title：”文件title”，original：”文件名称”，···}
                Ueditor msg = uploadFile(request);
                return JSONObject.toJSONString(msg);
            } else {
                ueditor.setState("文件为空");
                return JSON.toJSONString(ueditor);
            }
        } else {
            ueditor.setState("不支持该操作");
            return JSON.toJSONString(ueditor);
        }
    }

    private Ueditor uploadFile(HttpServletRequest request) {
        Ueditor image = new Ueditor();
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("upfile");
        try {
            String fileName = files.get(0).getOriginalFilename();
            if (files.get(0).getSize() > 5120000) {
                image.setState("Picture is too large,please choose new");
                image.setUrl("none");
                image.setOriginal(fileName);
                image.setTitle(fileName);
                return image;
            }
            logger.info("接收到上传数据，图片名称为 ：" + fileName);
            byte[] byt = files.get(0).getBytes();
            InputStream inputStream = new ByteArrayInputStream(byt);
            String directory = "plat/product/desc/";
            directory += System.currentTimeMillis() + "/";
            ResultDTO result = picUploadBService.uploadPicUnpressed(directory, fileName, inputStream);

            image.setUrl("");
            if (result.getStatusBool()) {
                image.setUrl(picUploadBService.getPicUrl(directory, fileName.toString()));
            }
            logger.info("图片上传成功,上传路径为 ：");

            image.setState("SUCCESS");
            image.setOriginal(fileName);
            image.setTitle(fileName);

        } catch (IOException e) {

            logger.error("图片上传失败，失败原因:" + e.getMessage());
            image.setState("FAIL");
        }
        return image;
    }
}
